document.addEventListener('DOMContentLoaded', async () => {
    let currentTag = '默认';
    let tagsData = {};

    // 加载默认标签的数据
    const loadDefaultData = async () => {
        try {
            const url = chrome.runtime.getURL('data/default.json');
            const response = await fetch(url);
            const data = await response.json();
            return data;
        } catch (error) {
            console.error('加载数据失败:', error);
            return null;
        }
    };

    // 保存数据到本地存储
    const saveData = async () => {
        const dataToSave = { ...tagsData };
        delete dataToSave['默认']; // 不保存默认标签数据
        await chrome.storage.local.set({ tagsData: dataToSave });
    };

    // 加载所有标签数据
    const loadAllData = async () => {
        try {
            const defaultData = await loadDefaultData();
            tagsData['默认'] = defaultData;

            // 从 chrome.storage 加载其他标签数据
            const result = await chrome.storage.local.get('tagsData');
            if (result.tagsData) {
                tagsData = { ...tagsData, ...result.tagsData };
            }
            return true;
        } catch (error) {
            console.error('加载数据失败:', error);
            return false;
        }
    };

    // 为通知项添加过渡效果
    document.querySelectorAll('.notification-item').forEach(item => {
        item.style.transition = 'all 0.3s ease-out';
    });

    // 添加右键菜单相关变量
    const contextMenu = document.querySelector('.context-menu');
    const editModal = document.querySelector('.edit-modal');
    let currentEditingIcon = null;

    // 显示右键菜单
    const showContextMenu = (e, asset, index) => {
        e.preventDefault();
        contextMenu.style.display = 'block';
        contextMenu.style.left = `${e.pageX}px`;
        contextMenu.style.top = `${e.pageY}px`;
        currentEditingIcon = { asset, index };
    };

    // 隐藏右键菜单
    document.addEventListener('click', () => {
        contextMenu.style.display = 'none';
    });

    // 处理右键菜单点击
    document.querySelector('.edit-icon').addEventListener('click', () => {
        showEditModal(currentEditingIcon.asset);
    });

    document.querySelector('.delete-icon').addEventListener('click', () => {
        const { asset, index } = currentEditingIcon;
        if (confirm(`确定要删除图标"${asset.name}"吗？`)) {
            deleteIcon(index);
        }
    });

    // 删除图标
    const deleteIcon = async (index) => {
        tagsData[currentTag].assets.splice(index, 1);
        await saveData();
        renderIcons(tagsData[currentTag].assets);
        showMessage('图标已删除');
    };

    // 显示编辑模态框
    const showEditModal = (asset) => {
        editModal.style.display = 'flex';
        document.getElementById('edit-icon-name').value = asset.name;
        document.getElementById('edit-icon-url').value = asset.url;
        document.getElementById('current-icon').src = asset.icon.startsWith('data:') 
            ? asset.icon 
            : chrome.runtime.getURL(`assets/${asset.icon}`);
    };

    // 处理编辑确认
    document.querySelector('.edit-confirm-btn').addEventListener('click', async () => {
        const iconFile = document.getElementById('edit-icon-upload').files[0];
        const name = document.getElementById('edit-icon-name').value;
        const url = document.getElementById('edit-icon-url').value;

        if (!name || !url) {
            alert('请填写完整信息');
            return;
        }

        const updateIcon = async (iconData) => {
            const { index } = currentEditingIcon;
            tagsData[currentTag].assets[index] = {
                name,
                url,
                icon: iconData || currentEditingIcon.asset.icon
            };
            await saveData();
            renderIcons(tagsData[currentTag].assets);
            editModal.style.display = 'none';
            showMessage('图标已更新');
        };

        if (iconFile) {
            const reader = new FileReader();
            reader.onloadend = () => updateIcon(reader.result);
            reader.readAsDataURL(iconFile);
        } else {
            await updateIcon();
        }
    });

    // 添加标签右键菜单相关变量
    const tagContextMenu = document.querySelector('.tag-context-menu');
    let currentRightClickedTag = null;

    // 显示标签右键菜单
    const showTagContextMenu = (e, tagName) => {
        e.preventDefault();
        tagContextMenu.style.display = 'block';
        tagContextMenu.style.left = `${e.pageX}px`;
        tagContextMenu.style.top = `${e.pageY}px`;
        currentRightClickedTag = tagName;
    };

    // 隐藏标签右键菜单
    document.addEventListener('click', () => {
        tagContextMenu.style.display = 'none';
        contextMenu.style.display = 'none'; // 同时处理图标的右键菜单
    });

    // 处理标签删除
    document.querySelector('.delete-tag').addEventListener('click', async () => {
        if (!currentRightClickedTag || currentRightClickedTag === '默认') {
            return;
        }

        // 检查标签下是否有图标
        const tagAssets = tagsData[currentRightClickedTag].assets;
        if (tagAssets && tagAssets.length > 0) {
            alert(`标签"${currentRightClickedTag}"下还有 ${tagAssets.length} 个图标，请先删除所有图标后再删除标签`);
            tagContextMenu.style.display = 'none';
            return;
        }

        // 确认删除
        if (confirm(`确定要删除标签"${currentRightClickedTag}"吗？`)) {
            // 如果正在查看要删除的标签，先切换到默认标签
            if (currentTag === currentRightClickedTag) {
                currentTag = '默认';
            }

            // 删除标签数据
            delete tagsData[currentRightClickedTag];
            
            // 保存更新后的数据
            await saveData();
            
            // 重新渲染标签列表
            renderTags();
            
            // 如果当前正在查看被删除的标签，切换到默认标签的内容
            if (currentTag === currentRightClickedTag) {
                renderIcons(tagsData['默认'].assets);
            }

            showMessage('标签已删除');
        }
        tagContextMenu.style.display = 'none';
    });

    // 修改渲染标签函数，添加右键菜单功能
    const renderTags = () => {
        const tagList = document.querySelector('.tag-list');
        tagList.innerHTML = '';
        
        Object.keys(tagsData).forEach(tagName => {
            const tagDiv = document.createElement('div');
            tagDiv.className = `tag ${tagName === currentTag ? 'active' : ''}`;
            tagDiv.textContent = tagName;
            
            // 添加左键点击事件
            tagDiv.addEventListener('click', () => switchTag(tagName));
            
            // 为非默认标签添加右键菜单
            if (tagName !== '默认') {
                tagDiv.addEventListener('contextmenu', (e) => {
                    e.preventDefault();
                    showTagContextMenu(e, tagName);
                });
            }
            
            tagList.appendChild(tagDiv);
        });
    };

    // 切换标签
    const switchTag = (tagName) => {
        currentTag = tagName;
        renderTags();
        renderIcons(tagsData[tagName].assets);
    };

    // 渲染图标
    const renderIcons = (assets) => {
        const iconsContainer = document.querySelector('.icons-container');
        iconsContainer.innerHTML = '';

        assets.forEach((asset, index) => {
            const iconItem = document.createElement('a');
            iconItem.href = asset.url;
            iconItem.target = '_blank';
            iconItem.className = 'icon-item';

            const img = document.createElement('img');
            if (asset.icon.startsWith('data:')) {
                img.src = asset.icon;
            } else {
                img.src = chrome.runtime.getURL(`assets/${asset.icon}`);
            }
            img.alt = asset.name;
            img.loading = 'lazy';

            const name = document.createElement('span');
            name.textContent = asset.name;

            iconItem.appendChild(img);
            iconItem.appendChild(name);

            // 为非默认图标添加右键菜单
            if (currentTag !== '默认' || index >= 3) {
                iconItem.addEventListener('contextmenu', (e) => {
                    e.preventDefault();
                    showContextMenu(e, asset, index);
                });
            }

            iconsContainer.appendChild(iconItem);
        });
    };

    // 显示消息提示
    const showMessage = (message) => {
        const messageTip = document.querySelector('.message-tip');
        messageTip.textContent = message;
        messageTip.style.display = 'block';
        setTimeout(() => {
            messageTip.style.display = 'none';
        }, 3000);
    };

    // 初始化
    const init = async () => {
        if (await loadAllData()) {
            renderTags();
            renderIcons(tagsData['默认'].assets);
        }
    };

    // 创建标签相关功能
    const tagModal = document.querySelector('.tag-modal');
    const createTagButton = document.querySelector('.create-tag-button');
    const tagConfirmBtn = document.querySelector('.tag-confirm-btn');
    const tagCancelBtn = document.querySelector('.tag-cancel-btn');

    // 显示创建标签模态框
    createTagButton.addEventListener('click', () => {
        tagModal.style.display = 'flex';
    });

    // 取消创建标签
    tagCancelBtn.addEventListener('click', () => {
        tagModal.style.display = 'none';
        document.getElementById('tag-name').value = '';
    });

    // 确认创建标签
    tagConfirmBtn.addEventListener('click', async () => {
        const tagName = document.getElementById('tag-name').value.trim();
        
        if (!tagName) {
            alert('请输入标签名称');
            return;
        }

        if (tagsData[tagName]) {
            alert('标签名称已存在');
            return;
        }

        // 创建新标签数���
        tagsData[tagName] = {
            tag: tagName,
            assets: []
        };

        // 保存数据
        await saveData();

        // 切换到新标签
        currentTag = tagName;
        renderTags();
        renderIcons([]);

        // 关闭弹窗和显示提示
        tagModal.style.display = 'none';
        document.getElementById('tag-name').value = '';
        showMessage('标签创建成功！');
    });

    // 新建图标相关功能
    const modal = document.querySelector('.modal');
    const addButton = document.querySelector('.add-button');
    const confirmBtn = document.querySelector('.confirm-btn');
    const cancelBtn = document.querySelector('.cancel-btn');

    // 显示新建图标模态框
    addButton.addEventListener('click', () => {
        modal.style.display = 'flex';
    });

    // 取消新建图标
    cancelBtn.addEventListener('click', () => {
        modal.style.display = 'none';
        resetForm();
    });

    // 重置表单
    const resetForm = () => {
        document.getElementById('icon-upload').value = '';
        document.getElementById('icon-name').value = '';
        document.getElementById('icon-url').value = '';
    };

    // 确认新建图标
    confirmBtn.addEventListener('click', async () => {
        const iconFile = document.getElementById('icon-upload').files[0];
        const name = document.getElementById('icon-name').value.trim();
        const url = document.getElementById('icon-url').value.trim();

        if (!iconFile || !name || !url) {
            alert('请填写完整信息');
            return;
        }

        // 将图标文件转换为Base64
        const reader = new FileReader();
        reader.onloadend = async () => {
            // 创建新的图标数据
            const newIcon = {
                name: name,
                url: url,
                icon: reader.result
            };

            // 添加到当前标签的资产中
            tagsData[currentTag].assets.push(newIcon);
            
            // 保存数据
            await saveData();

            // 重新渲染图标
            renderIcons(tagsData[currentTag].assets);

            // 关闭弹窗并显示提示
            modal.style.display = 'none';
            resetForm();
            showMessage('图标创建成功！');
        };
        reader.readAsDataURL(iconFile);
    });

    // 搜索功能
    const searchInput = document.querySelector('.search-input');
    
    // 实时搜索过滤图标
    searchInput.addEventListener('input', (e) => {
        const searchTerm = e.target.value.trim().toLowerCase();
        const currentAssets = tagsData[currentTag].assets;
        
        if (searchTerm === '') {
            renderIcons(currentAssets);
            return;
        }

        const filteredAssets = currentAssets.filter(asset => {
            const name = asset.name.toLowerCase();
            const url = asset.url.toLowerCase();
            return name.includes(searchTerm) || url.includes(searchTerm);
        });

        renderIcons(filteredAssets);
    });

    // 回车搜索功能
    searchInput.addEventListener('keyup', (e) => {
        if (e.key === 'Enter') {
            const searchTerm = searchInput.value.trim();
            if (searchTerm) {
                window.open(`https://www.baidu.com/s?wd=${encodeURIComponent(searchTerm)}`, '_blank');
            }
        }
    });

    init();
}); 